import { createStore, applyMiddleware, combineReducers } from 'redux'
// redux-thunk的作用: 帮我们在redux中实现异步
import thunk from 'redux-thunk'
// 使用调用工具的同时使用中间件的包
import { composeWithDevTools } from 'redux-devtools-extension'

// 定义reducer函数
function zsReducer(state = { count: 1, msg: 'hello' }, action) {
  switch (action.type) {
    case 'add':
      const newCount = state.count + 1
      return {
        ...state,
        count: newCount,
      }
    case 'sub':
      return {
        ...state,
        count: state.count - 1,
      }
    // 注意: redux中reducer函数必须写default.default的代码是固定的.必须是return state. 因为有了这段代码才能初始化数据
    default:
      return state
  }
}

function lsReducer(state = { list: [1, 2, 3] }, action) {
  switch (action.type) {
    case 'push':
      state.list.push(action.xxx)
      return {
        ...state,
        list: state.list,
      }
    default:
      return state
  }
}

// 由于创建store对象时,只能传入一个reducer函数.所以就必须将多个reducer合并成一个reducer

const rootReducer = combineReducers({
  zs: zsReducer,
  ls: lsReducer,
})

// 创建store的同时配置中间件和redux调试工具
const store = createStore(
  rootReducer,
  composeWithDevTools(applyMiddleware(thunk))
)

// 监听redux数据变化
store.subscribe(() => {
  console.log(store.getState())
})

store.dispatch({ type: 'add' })

store.dispatch({ type: 'push', xxx: '999' })
store.dispatch({ type: 'push', xxx: '999' })
